<?php
App::import('Model', 'Gaji');

class GajiBL extends Gaji {

    public function createGaji($data = array(), $dataSession = array()) {
        $ret = null;
        if (!empty($data['Payroll']['divisi_id']) && ($data['Gaji']['karyawan_id'])==0) {
            $divisiId = $data['Payroll']['divisi_id'];
            return $this->addByDivisi($data, $divisiId);
        } else if (!empty($data['Payroll']['divisi_id']) && ($data['Gaji']['karyawan_id'])!=0) {
            return $this->addByKaryawan($data);
        }
    }

    public function addByDivisi($data = array(), $divisiId = NULL) {
        $ret = null;
        $arrayKaryawanToInsert = $this->Karyawan->query('SELECT * FROM karyawan WHERE divisi_id = ' . $divisiId . ' AND id NOT IN (SELECT karyawan_id FROM gaji)');

        foreach ($arrayKaryawanToInsert as $karyawan) {
            //pr($karyawan['karyawan']['id']);
            $data['Gaji']['karyawan_id'] = $karyawan['karyawan']['id'];
            //pr($data
            $this->create();
            if ($this->save($data)) {
                $ret = true;
            } else {
                $ret = false;
            }
        }

        return $ret;
    }

    function addByKaryawan($data = array()) {
        $ret = false;

        $this->create();
        if ($this->save($data)) {
            $ret = true;
        }
        
        return $ret;
    }

    function editGaji($data = array(), $id = null) {
        $ret = null;
            if ($this->save($data)) {
                $ret = true;
            } else {
                $ret = false;
            }
        return $ret;
    }

    function deleteGaji($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for gaji', true));
            $this->redirect(array('action' => 'index'));
        }
        if ($this->Gaji->delete($id)) {
            $this->Session->setFlash(__('Gaji deleted', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Gaji was not deleted', true));
        $this->redirect(array('action' => 'index'));
    }

    public function readDetail($id = null){
        return $this->read(null, $id);
    }
    
}

?>
